package com.tarena.lbs.business.controller;

import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.pojo.query.StoreChainQuery;
import com.tarena.lbs.business.pojo.vo.StoreChainVO;
import com.tarena.lbs.business.service.StoreChainService;
import com.tarena.lbs.business.service.impl.QRCodeUtil;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

@Tag(name="二维码相关功能接口")
@RestController
public class StoreChainController {
    @Autowired
    private StoreChainService storeChainService;

    @DubboReference
    private UserApi userApi;

    @Operation(summary = "二维码列表页")
    @PostMapping("/admin/basic/chain/getAll")
    public Result<PageResult<StoreChainVO>> pageList(@RequestBody StoreChainQuery query)
            throws BusinessException {
        //查询当前商家下商铺的二维码
        Integer businessId = getLoginId();
        if(businessId!=null && businessId>0){
            query.setBusinessId(businessId);
        }

        PageResult<StoreChainVO> pageResult = storeChainService.pageList(query);
        return new Result<>(pageResult);
    }


    @Operation(summary = "查看店铺二维码")
    @PostMapping("/admin/basic/chain/qrcode-with-logo")
    public ResponseEntity<byte[]> generateQRCodeWithLogo(@RequestBody StoreChainQuery query) {
        try {
            // 读取logo图片
            URL url = new URL(query.getLinkImage());
            URLConnection conn = url.openConnection();
            InputStream stream = conn.getInputStream();
            BufferedImage image = ImageIO.read(stream);

            byte[] imageData = QRCodeUtil.generateQRCodeWithLogo(query.getLink(),image);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);

            return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @Operation(summary = "启用二维码")
    @PutMapping("/admin/basic/chain/enable/{id}")
    public Result<Void> enableQRCode(@PathVariable("id") Integer id) {
        storeChainService.enableQRCode(id);
        return Result.success();
    }

    @Operation(summary = "禁用二维码")
    @PutMapping("/admin/basic/chain/disable/{id}")
    public Result<Void> disableQRCode(@PathVariable("id") Integer id) {
        storeChainService.disableQRCode(id);
        return Result.success();
    }







// 获取当前登录用户ID
    private Integer getLoginId() throws BusinessException {
        // 1. 获取当前用户认证信息
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();

        // 2. 检查用户是否已认证 - 完全移除Asserts.isTrue()，使用标准if条件判断
        if (userPrinciple == null) {
            throw new BusinessException("-2", "用户认证解析失败");
        }

        AdminDto adminDto = null;
        // 3. 权限细化：商家只能查询自己的店铺
        if(userPrinciple.getRole() == Roles.SHOP){
            //假设商家ID存储在UserPrinciple的扩展字段中
            adminDto = userApi.getAdminById(userPrinciple.getId());
            // 判断商家信息是否为空
            if (adminDto == null) {
                throw new BusinessException("500", "商家信息不存在");
            }
        } else if (userPrinciple.getRole() == Roles.ADMIN) {
            // 管理员可以查看所有商家的二维码，不需要设置businessId
            return null;
        } else {
            // 非商家、非管理员角色，无权限访问此功能
            throw new BusinessException("403", "当前用户无权限访问此功能");
        }

        return adminDto.getBusinessId();
}
}
